import { createParamDecorator, ExecutionContext } from '@nestjs/common'
import { isObject, isArray, isString, isUndefined } from 'lodash'
import { Like, Equal } from 'typeorm'

// 自定义查询的 where和order条件
export interface IParamsConfig {
  where?: string[] | object
  order?: {
    [key: string]: 'DESC' | 'ASC'
  }
}
/**
 * 返回结构
 * pageParams页码参数；where条件；order条件；
 */
export interface IParamsResult {
  pageParams: {
    page: number
    limit: number
  }
  where: any
  order: { [key: string]: 'DESC' | 'ASC' }
}

export const ListParams = createParamDecorator((customConfig: IParamsConfig, ctx: ExecutionContext): IParamsResult => {
  const request = ctx.switchToHttp().getRequest()
  const { query } = request
  const { page, limit, orderBy, orderValue } = query
  const { where: whereOptions, order: defaultOrder } = customConfig
  const conditionMap: any = { Equal }
  const pageParams = {
    page: Number(page || 1),
    limit: Number(limit || 10),
  }
  const where = {}
  let order = {}

  if (!isObject(customConfig)) {
    return { pageParams, where, order }
  }

  if (isArray(whereOptions)) {
    whereOptions.forEach((item) => {
      if (!isUndefined(item) && (query[item] || query[item['field']])) {
        const field = isString(item) ? item : item['field']
        // 对string和object参数分别处理
        where[field] = isString(item) ? Like(`%${query[item]}%`) : conditionMap[item['condition']](`${query[item['field']]}`)
      }
    })
  }

  // 处理order默认条件
  if (isObject(defaultOrder)) {
    order = defaultOrder
  }

  // 处理前端传来的order条件
  if (isString(orderBy)) {
    if (['DESC', 'ASC'].includes(orderValue)) {
      order = { [query.orderBy]: orderValue }
    }
  }

  return { pageParams, where, order }
})
